package com.chris.oauth2.web.oauth2;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.chris.oauth2.service.AuthService;
import com.chris.oauth2.util.IdUtil;
import com.chris.oauth2.util.MD5Util;

@Controller
@RequestMapping("oauth2")
public class AccessTokenController {

	@Autowired
	AuthService authService;

	@RequestMapping("access_token")
	@Transactional
	public @ResponseBody Object access_token(@RequestParam String appid, @RequestParam String secret,
			@RequestParam String code, @RequestParam String grant_type) {
		Map<String, Object> rs = new HashMap<>();
		if (!authService.checkClientId(appid)) {
			rs.put("errcode", 201);
			rs.put("errmsg", "invalid appid");
			return rs;
		}
		if (!authService.checkClientSecret(secret)) {
			rs.put("errcode", 202);
			rs.put("errmsg", "invalid secret");
			return rs;
		}
		if (StringUtils.isBlank(grant_type) || !"openapi".equals(grant_type)) {
			rs.put("errcode", 203);
			rs.put("errmsg", "invalid grant_type");
			return rs;
		}
		String clientIdByAuthCode;
		if ((clientIdByAuthCode = authService.checkAuthCode(code)) == null || !appid.equals(clientIdByAuthCode)) {
			rs.put("errcode", 204);
			rs.put("errmsg", "invalid code");
			return rs;
		}

		String accessToken = MD5Util.encode((IdUtil.generateId() + code).getBytes());
		String refreshToken = MD5Util.encode((IdUtil.generateId() + appid + secret).getBytes());
		authService.addAccessToken(accessToken, appid);
		authService.addRefreshToken(refreshToken, appid);
		rs.put("access_token", accessToken);
		rs.put("refresh_token", refreshToken);
		rs.put("expires_in", authService.getExpireIn());
		return rs;
	}

}
